package com.ptu.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.ptu.dto.OrderPayDTO;
import com.ptu.server.OrderServer;
import com.ptu.util.PayUtil;
import com.ptu.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Map;

@Controller
@RequestMapping("/api/alipay")
public class AliPayController {
    @Autowired
    private PayUtil payUtil;
    @Autowired
    private OrderServer orderServer;
    @ResponseBody
    @Operation(summary = "支付订单")
    @PostMapping("/pay")
    public String alipay(@RequestBody OrderPayDTO orderPayDTO) throws AlipayApiException {
        //调用封装好的方法（给支付宝接口发送请求）
        System.out.println("支付订单");
        //获取订单号
        String orderNo = orderPayDTO.getOrderNo();
        //获取订单价格
        float oderValue = orderPayDTO.getActualAmount().floatValue();
        //定义订单名
        String orderName = ("订单支付"+ orderPayDTO.getOrderNo()) ;
        System.out.println("订单支付成功");
        orderServer.payByOrderNo(orderNo);
        //返回html表单
        return payUtil.sendRequestToAlipay(orderNo, oderValue, orderName);

    }

    //当我们支付完成之后跳转这个请求，传入订单id，通过订单id查询订单信息，信息包括支付是否成功等
    @GetMapping("/toSuccess")
    public String returns(@RequestParam String orderNo, @RequestParam(required = false) BigDecimal totalAmount) throws ParseException {
        String query = payUtil.query(orderNo);
        System.out.println("==>" + query);
        JSONObject jsonObject = JSONObject.parseObject(query);
        Object o = jsonObject.get("alipay_trade_query_response");
        Map map = (Map) o;
        System.out.println(map);
        Object s = map.get("trade_status");
        if (s.equals("TRADE_SUCCESS")) {
            //当支付成功之后要执行的操作，跳转到支付成功页，修改订单状态为已支付
            System.out.println("订单支付成功");
            orderServer.payByOrderNo(orderNo);
            System.out.println(s);
            return "redirect:http://localhost:5173/orders";
        } else {
           // 支付失败要执行的操作，返回支付失败消息，跳转到订单列表页
            System.out.println("订单支付失败");
            return "redirect:http://localhost:5173/orders";
        }
    }

    /*
参数1：订单号
参数2：订单金额
参数3：订单名称
 */

}